package com.newear.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.newear.MyApplication;
import com.newear.R;
import com.newear.bean.ReportInfo;
import com.newear.constant.DataType;
import com.newear.constant.RequireParams;
import com.newear.happyDialog.CamaraCheckDialog;
import com.newear.message.MessageDispatcher;
import com.newear.message.MessageType;
import com.newear.util.HardWare;
import com.newear.util.MyLogger;
import com.newear.util.ProgressDialogUtil;
import com.newear.util.T;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class HappyLastMultiSelectActivity extends AppCompatActivity {
    private static final String TAG = "HappyLastMultiSelectAct";
    private LinearLayout lL_last_multi_select_container;
    private ArrayList mLastMultiTextList;
    private ArrayList<String> mFirstButtonTextList;
    private ArrayList<String> mSecondButtonTextList;
    private ArrayList<String> mThirdButtonTextList;
    private ArrayList<String> mFourthButtonTextList;
    private ArrayList<String> mFiveButtonTextList;
    private ArrayList<String> mSixthButtonTextList;
    private ArrayList<String> mSevenButtonTextList;
    private ArrayList<String> mEightButtonTextList;
    private Context mContext;
    private Button btnReviewReport;
    private String key;
    private MyHandler myHandler;
    private ProgressDialog mProgressDialog; //网络请求时用的进度条

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_happy_last_multi_select);
        init();
        findViews();
        setListeners();
        addLastMultiBtns();
    }

    private void init(){
        HardWare.registerActivity(this);
        this.mContext = this;
        this.key = this.hashCode() + "";
        myHandler = new MyHandler(this);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        //button的数据
        mLastMultiTextList = new ArrayList();

        mFirstButtonTextList = new ArrayList();
        mFirstButtonTextList.add("肥胖");
        mFirstButtonTextList.add("高血压");
        mFirstButtonTextList.add("高尿酸");

        mSecondButtonTextList = new ArrayList();
        mSecondButtonTextList.add("脂肪肝");
        mSecondButtonTextList.add("贫血");
        mSecondButtonTextList.add("口气");

        mThirdButtonTextList = new ArrayList();
        mThirdButtonTextList.add("咽炎");
        mThirdButtonTextList.add("眼干");
        mThirdButtonTextList.add("健忘");

        mFourthButtonTextList = new ArrayList();
        mFourthButtonTextList.add("失眠");
        mFourthButtonTextList.add("免疫力差");
        mFourthButtonTextList.add("易疲劳");

        mFiveButtonTextList = new ArrayList();
        mFiveButtonTextList.add("泌尿系统炎症");
        mFiveButtonTextList.add("大便不爽/便秘");
        mFiveButtonTextList.add("腰酸无力");

        mSixthButtonTextList = new ArrayList();
        mSixthButtonTextList.add("前列腺问题");
        mSixthButtonTextList.add("更年期（女）");
        mSixthButtonTextList.add("更年期（男）");

        mSevenButtonTextList = new ArrayList();
        mSevenButtonTextList.add("皮肤暗沉");
        mSevenButtonTextList.add("面部色斑");
        mSevenButtonTextList.add("皮肤干燥");

        mEightButtonTextList = new ArrayList();
        mEightButtonTextList.add("皮肤多油（女）");
        mEightButtonTextList.add("皮肤多油（男）");
        mEightButtonTextList.add("皮肤过敏");

        mLastMultiTextList.add(mFirstButtonTextList);
        mLastMultiTextList.add(mSecondButtonTextList);
        mLastMultiTextList.add(mThirdButtonTextList);
        mLastMultiTextList.add(mFourthButtonTextList);
        mLastMultiTextList.add(mFiveButtonTextList);
        mLastMultiTextList.add(mSixthButtonTextList);
        mLastMultiTextList.add(mSevenButtonTextList);
        mLastMultiTextList.add(mEightButtonTextList);
        if (MyApplication.sCustomerInfo.multiSelect2 == null) {
            MyApplication.sCustomerInfo.multiSelect2 = new int[2];
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HardWare.registerActivity(this);
    }

    private void findViews(){
        lL_last_multi_select_container = (LinearLayout) findViewById(R.id.lL_last_multi_select_container);
        btnReviewReport = (Button) findViewById(R.id.btn_review_report);
    }

    private void setListeners(){
        btnReviewReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MyApplication.sCustomerInfo.multiSelect2[0] == 0) {
                    CamaraCheckDialog camaraCheckDialog = new CamaraCheckDialog(mContext, R.style.dialog, "请先完成选项", "再查看报告", -1);
                    camaraCheckDialog.show();
                    return;
                }
                getReport();
            }
        });
    }

    private void addLastMultiBtns(){
        if (lL_last_multi_select_container != null){
            lL_last_multi_select_container.removeAllViews();
        }

        for (int i = 0; i < mLastMultiTextList.size(); i++) {
            View view = View.inflate(this, R.layout.happy_last_multi_button, null);
            final Button leftBtn = (Button) view.findViewById(R.id.btn_multi_left);
            final Button middleBtn = (Button) view.findViewById(R.id.btn_multi_middle);
            final Button rightBtn = (Button) view.findViewById(R.id.btn_multi_right);
            if (MyApplication.sCustomerInfo.multiSelect2[0] > 0 || MyApplication.sCustomerInfo.multiSelect2[0] > 0) {
                int leftIndex = i * 3 + 1;
                int middle = i * 3 + 2;
                int rightIndex = i * 3 + 3;
                if (MyApplication.sCustomerInfo.multiSelect2[0] > 0) {
                    if (MyApplication.sCustomerInfo.multiSelect2[0] == leftIndex) {
                        leftBtn.setSelected(true);
                    } else if (MyApplication.sCustomerInfo.multiSelect2[0] == middle) {
                        middleBtn.setSelected(true);
                    } else if (MyApplication.sCustomerInfo.multiSelect2[0] == rightIndex) {
                        rightBtn.setSelected(true);
                    }
                }
                if (MyApplication.sCustomerInfo.multiSelect2[1] > 0) {
                    if (MyApplication.sCustomerInfo.multiSelect2[1] == leftIndex) {
                        leftBtn.setSelected(true);
                    } else if (MyApplication.sCustomerInfo.multiSelect2[1] == middle) {
                        middleBtn.setSelected(true);
                    } else if (MyApplication.sCustomerInfo.multiSelect2[1] == rightIndex) {
                        rightBtn.setSelected(true);
                    }
                }
            }
            view.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            lL_last_multi_select_container.addView(view);

            ArrayList<String> buttonTitleList = (ArrayList) mLastMultiTextList.get(i);
            leftBtn.setText(buttonTitleList.get(0));
            middleBtn.setText(buttonTitleList.get(1));
            rightBtn.setText(buttonTitleList.get(2));

            final int finalI = i;
            leftBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int index = finalI * 3 + 1;
                    if (!leftBtn.isSelected()) {
                        // 选中
                        if (MyApplication.sCustomerInfo.multiSelect2[0] > 0
                                && MyApplication.sCustomerInfo.multiSelect2[1] > 0) {
                            // 已经选中两个，不能再选
                            Toast.makeText(mContext, "最多只能选择两个选项！", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (MyApplication.sCustomerInfo.multiSelect2[0] > 0
                                && MyApplication.sCustomerInfo.multiSelect2[1] == 0){
                            // 只选了一个
                            if (MyApplication.sCustomerInfo.multiSelect2[0] < index) {
                                MyApplication.sCustomerInfo.multiSelect2[1] = index;
                            } else {
                                MyApplication.sCustomerInfo.multiSelect2[1] = MyApplication.sCustomerInfo.multiSelect2[0];
                                MyApplication.sCustomerInfo.multiSelect2[0] = index;
                            }
                        } else {
                            // 没有选择
                            MyApplication.sCustomerInfo.multiSelect2[0] = index;
                        }
                        leftBtn.setSelected(true);
                    } else {
                        if (MyApplication.sCustomerInfo.multiSelect2[0] == index ) {
                            MyApplication.sCustomerInfo.multiSelect2[0] = MyApplication.sCustomerInfo.multiSelect2[1];
                            MyApplication.sCustomerInfo.multiSelect2[1] = 0;
                        } else {
                            MyApplication.sCustomerInfo.multiSelect2[1] = 0;
                        }
                        leftBtn.setSelected(false);
                    }
                }
            });

            middleBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int index = finalI * 3 + 2;
                    if (!middleBtn.isSelected()) {
                        // 选中
                        if (MyApplication.sCustomerInfo.multiSelect2[0] > 0
                                && MyApplication.sCustomerInfo.multiSelect2[1] > 0) {
                            // 已经选中两个，不能再选
                            Toast.makeText(mContext, "最多只能选择两个选项！", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (MyApplication.sCustomerInfo.multiSelect2[0] > 0
                                && MyApplication.sCustomerInfo.multiSelect2[1] == 0){
                            // 只选了一个
                            if (MyApplication.sCustomerInfo.multiSelect2[0] < index) {
                                MyApplication.sCustomerInfo.multiSelect2[1] = index;
                            } else {
                                MyApplication.sCustomerInfo.multiSelect2[1] = MyApplication.sCustomerInfo.multiSelect2[0];
                                MyApplication.sCustomerInfo.multiSelect2[0] = index;
                            }
                        } else {
                            // 没有选择
                            MyApplication.sCustomerInfo.multiSelect2[0] = index;
                        }
                        middleBtn.setSelected(true);
                    } else {
                        if (MyApplication.sCustomerInfo.multiSelect2[0] == index ) {
                            MyApplication.sCustomerInfo.multiSelect2[0] = MyApplication.sCustomerInfo.multiSelect2[1];
                            MyApplication.sCustomerInfo.multiSelect2[1] = 0;
                        } else {
                            MyApplication.sCustomerInfo.multiSelect2[1] = 0;
                        }
                        middleBtn.setSelected(false);
                    }
                }
            });

            rightBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int index = finalI * 3 + 3;
                    if (!rightBtn.isSelected()) {
                        // 选中
                        if (MyApplication.sCustomerInfo.multiSelect2[0] > 0
                                && MyApplication.sCustomerInfo.multiSelect2[1] > 0) {
                            // 已经选中两个，不能再选
                            Toast.makeText(mContext, "最多只能选择两个选项！", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (MyApplication.sCustomerInfo.multiSelect2[0] > 0
                                && MyApplication.sCustomerInfo.multiSelect2[1] == 0){
                            // 只选了一个
                            if (MyApplication.sCustomerInfo.multiSelect2[0] < index) {
                                MyApplication.sCustomerInfo.multiSelect2[1] = index;
                            } else {
                                MyApplication.sCustomerInfo.multiSelect2[1] = MyApplication.sCustomerInfo.multiSelect2[0];
                                MyApplication.sCustomerInfo.multiSelect2[0] = index;
                            }
                        } else {
                            // 没有选择
                            MyApplication.sCustomerInfo.multiSelect2[0] = index;
                        }
                        rightBtn.setSelected(true);
                    } else {
                        if (MyApplication.sCustomerInfo.multiSelect2[0] == index ) {
                            MyApplication.sCustomerInfo.multiSelect2[0] = MyApplication.sCustomerInfo.multiSelect2[1];
                            MyApplication.sCustomerInfo.multiSelect2[1] = 0;
                        } else {
                            MyApplication.sCustomerInfo.multiSelect2[1] = 0;
                        }
                        rightBtn.setSelected(false);
                    }
                }
            });

        }

    }

    /**
     * 查看报告
     */
    private void getReport() {
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(RequireParams.DATA_TYPE, DataType.GET_REPORT);
        param.put(RequireParams.MAP_KEY, this.key + DataType.GET_REPORT);
        param.put(RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    private void showReport(ReportInfo reportInfo) {
        MyApplication.sReportInfo = reportInfo;
        MyLogger.e("展示报告！");
        //这边跳转到报告结果页面,关闭掉之前除了首页的所有页面
        Intent intent = new Intent(HappyLastMultiSelectActivity.this, HappyReportActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        startActivity(intent);
        HardWare.finishAllActivity();
    }

    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final HappyLastMultiSelectActivity activity = (HappyLastMultiSelectActivity) mActivityReference.get();
                if (activity != null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:   //显示对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.setMessage("正在获取报告...");
                                activity.mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (activity.mProgressDialog != null) {
                                activity.mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.GET_REPORT) {
                                SparseArray<Object> result = (SparseArray<Object>) msg.obj;
                                String errno = (String) result.get(0);
                                if ("0".equals(errno)) {
                                    ReportInfo reportInfo = (ReportInfo) result.get(1);
                                    if (reportInfo != null) {
                                        activity.showReport(reportInfo);
                                    }
                                } else if ("1".equals(errno)){
                                    String errMsg = (String) result.get(1);
                                    T.shortToast(activity, errMsg);
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                MyLogger.e(TAG, "handleMessage Exception!e:" + e.getMessage());
            }
        }
    }

}
